<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>查找 - MdbSystem</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/mdui@2.1.3/mdui.min.css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <style>
    body {
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-color: #f5f5f5;
      font-family: Arial, sans-serif;
      background-repeat: no-repeat;
      background-attachment: fixed;
      background-size: cover;
      background-image: url("https://www.dmoe.cc/random.php?233335556958");
      position: relative;
    }
    body::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(255, 255, 255, 0.9);
      z-index: 1;
    }
    .search-container {
      width: 80%;
      max-width: 600px;
      padding: 20px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      text-align: center;
      position: relative;
      z-index: 2;
    }
    .title {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 20px;
    }
    .mdui-textfield {
      width: 100%;
      display: flex;
      align-items: center;
      position: relative;
    }
    .mdui-textfield-input {
      font-size: 16px;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
      flex: 1;
      margin-right: 10px;
    }
    .mdui-btn-search {
      background-color: #007bff;
      color: white;
      border-radius: 4px;
      padding: 10px 20px;
      border: none;
      cursor: pointer;
      transition: background-color 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .mdui-btn-search:hover {
      background-color: #0056b3;
    }
    .mdui-btn-upload-page {
      background-color: #4CAF50;
      color: white;
      border-radius: 4px;
      padding: 10px 20px;
      margin-top: 20px;
      border: none;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }
    .mdui-btn-upload-page:hover {
      background-color: #45a049;
    }
    .suggestions-dropdown {
      position: absolute;
      top: 100%;
      left: 0;
      width: 100%;
      background: white;
      border: 1px solid #ccc;
      border-top: none;
      border-radius: 0 0 4px 4px;
      list-style: none;
      padding: 0;
      margin: 0;
      z-index: 3;
      display: none;
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    .suggestions-dropdown li {
      padding: 10px;
      cursor: pointer;
      transition: background-color 0.2s;
      text-align: left;
    }
    .suggestions-dropdown li:hover {
      background-color: #f5f5f5;
    }
  </style>
</head>
<body>
  <div class="search-container">
    <div class="title">通过ID查找题目、知识点🔎</div>
    <div class="mdui-textfield">
      <input class="mdui-textfield-input" type="text" placeholder="请输入搜索内容">
      <button class="mdui-btn-search" onclick="searchAction()">
        <i>GO✨</i>
      </button>
      <ul id="suggestions-list" class="suggestions-dropdown"></ul>
    </div>
    <ul id="search-results"></ul>
    <button class="mdui-btn-upload-page" onclick="goToUploadPage()">
      👆 添加题目
    </button>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/mdui@2.1.3/mdui.global.min.js"></script>
  <script>
    function debounce(func, delay) {
      let timeoutId;
      return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func.apply(this, args), delay);
      };
    }

    async function fetchSuggestions(query) {
      try {
        const response = await fetch(`/searchEngine?keyword=${encodeURIComponent(query)}`);
        const result = await response.json();

        const suggestionsList = document.getElementById('suggestions-list');
        if (result.error_code === 0 && result.result.length > 0) {
          const items = result.result.slice(0, 5);
          suggestionsList.innerHTML = items.map(item =>
            `<li data-id="${item[0]}">${item[2]} - [ID:${item[0]}]</li>`
          ).join('');
          suggestionsList.style.display = 'block';
        } else {
          suggestionsList.style.display = 'none';
        }
      } catch (error) {
        console.error('获取提示词失败:', error);
      }
    }

    async function searchAction() {
      const input = document.querySelector('.mdui-textfield-input');
      const query = input.value.trim();

      if (!query) {
        mdui.snackbar({
          message: '请输入要搜索的关键词',
          position: 'right-top',
          timeout: 2000
        });
        return;
      }

      try {
        const response = await fetch(`/searchEngine?keyword=${encodeURIComponent(query)}`);
        const result = await response.json();

        const searchResult = document.querySelector('#search-results');
        if (result.error_code === 1) {
          mdui.snackbar({
            message: '内容不存在，请检查关键词是否正确',
            position: 'right-top',
            timeout: 3000
          });
        } else if (result.error_code === 0) {
          let searchResponse = result.result
          searchResult.innerHTML = ''
          searchResult.innerHTML += "<li>查询到以下内容，点击访问：</li>"
          for (let i=0; i<searchResponse.length; i++){
            searchResult.innerHTML += "<li>"+ `<a href="/detailDataPage?id=${searchResponse[i][0]}">`+searchResponse[i][2]+"</a>"+"</li>"
          }
        }
      } catch (error) {
        mdui.snackbar({
          message: '搜索失败，请检查网络连接',
          position: 'right-top',
          timeout: 3000
        });
        console.error('搜索错误:', error);
      }
    }
    document.getElementById('suggestions-list').addEventListener('click', function(e) {
      const li = e.target.closest('li');
      if (li) {
        const itemId = li.getAttribute('data-id');
        if (itemId) {
          window.location.href = `/detailDataPage?id=${itemId}`;
        }
      }
    });

    document.querySelector('.mdui-textfield-input').addEventListener('input',
      debounce(function(e) {
        const query = e.target.value.trim();
        if (query) {
          fetchSuggestions(query);
        } else {
          hideSuggestions();
        }
      }, 300)
    );

    document.addEventListener('click', function(e) {
      if (!e.target.closest('.mdui-textfield')) {
        hideSuggestions();
      }
    });

    function hideSuggestions() {
      document.getElementById('suggestions-list').style.display = 'none';
    }

    function goToUploadPage() {
      window.location.href = "publish";
    }

    document.querySelector('.mdui-textfield-input').addEventListener('keypress', function(e) {
      if (e.key === 'Enter') {
        searchAction();
      }
    });
  </script>
</body>
</html>